package com.hzvdvmc.autosale.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.hzvdvmc.autosale.MyApp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by william on 2018/1/21.
 */

public class LogToFileHelper {
    private static String TAG = "LogToFileHelper";
    private static String logPath = null;//log日志存放路径
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//日期格式;
    private static SimpleDateFormat dateFormatForLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式;

    public static String getLogPath() {
        return logPath;
    }

    private static Executor executor = Executors.newSingleThreadExecutor();

    /**
     * 初始化，须在使用之前设置，最好在Application创建时调用
     *
     * @param context
     */
    public static void init(Context context) {
        logPath = getFilePath(context) + "/Logs";//获得文件储存路径,在后面加"/Logs"建立子文件夹
        //如果父路径不存在
        File file = new File(logPath);
        if (!file.exists()) {
            file.mkdirs();//创建父路径
        }
    }

    /**
     * 获得文件存储路径
     *
     * @return
     */
    private static String getFilePath(Context context) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || !Environment.isExternalStorageRemovable()) {
            //如果外部储存可用
            return context.getExternalFilesDir(null).getPath();
            //获得外部存储路径,默认路径为
            // /storage/emulated/0/Android/data/com.waka.workspace.logtofile/files/Logs/log_2016-03-14_16-15-09.log
        } else {
            return context.getFilesDir().getPath();
            //直接存在/data/data里，非root手机是看不到的
        }
    }

    private static final char VERBOSE = 'v';

    private static final char DEBUG = 'd';

    private static final char INFO = 'i';

    private static final char WARN = 'w';

    private static final char ERROR = 'e';

    public static void v(String tag, String msg) {
        writeToFile(VERBOSE, tag, msg, false);
    }

    public static void d(String tag, String msg) {
        writeToFile(DEBUG, tag, msg, false);
    }

    public static void i(String tag, String msg) {
        writeToFile(INFO, tag, msg, false);
    }

    public static void i(String msg) {
        writeToFile(INFO, "", msg, false);
    }

    public static void e(String tag, String msg) {
        writeToFile(ERROR, tag, msg, true);
    }

    /**
     * 将log信息写入文件中
     *
     * @param type
     * @param tag
     * @param msg
     */
    private static void writeToFile(final char type, final String tag, final String msg, final boolean isCrash) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                writeToLocal(isCrash, type, tag, msg);
            }
        });
    }

    private synchronized static void writeToLocal(boolean isCrash, char type, String tag, String msg) {
        if (null == logPath) {
            Log.e(TAG, "logPath == null ，未初始化LogToFile");
            return;
        }

        String crash = "";
        if (isCrash) {
            crash = "crash";
        }

        String fileName = logPath + File.separator
                + dateFormat.format(new Date()) + crash + ".log";//log日志名，使用时间命名，保证不重复
        File logFile = new File(fileName);

        String log = dateFormatForLog.format(new Date())
                + "[" + type + "]" + tag + ":\n" + msg + "\n";//log日志内容，可以自行定制
        FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法，不用关闭
        BufferedWriter bw = null;
        try {
            if (!logFile.exists()) {
                logFile.createNewFile();
            }

            fos = new FileOutputStream(fileName, true);//这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
            bw = new BufferedWriter(new OutputStreamWriter(fos));
            bw.write(log);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();//关闭缓冲流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String ReadFile(String strFilePath) {

        StringBuilder sb = new StringBuilder();
        //打开文件
        File file = new File(strFilePath);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (!file.exists()) {
            ToastUtils.showShort("文件错误");
        }
        try {
            InputStream instream = new FileInputStream(file);
            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;
                //分行读取

                while ((line = buffreader.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }
                instream.close();
            }
        } catch (java.io.FileNotFoundException e) {
            Log.d("TestFile", "The File doesn't not exist.");
        } catch (IOException e) {
            Log.d("TestFile", e.getMessage());
        }
        return sb.toString();
    }
}
